<?php

define('SECURITY_TOKEN_WORD_0', '02a1v1a8Gb9666ad1de7029668df86c1');
define('SECURITY_TOKEN_WORD_1', '922ec9531b1f94add983A8ce2ebdc97b');
define('SECURITY_TOKEN_WORD_2', 'acf7ef943fdeb3cbfeY8dd0d8f584731');
define('SECURITY_TOKEN_WORD_3', '5a8dccb220De5c6775c873ead6ff2e43');
define('SECURITY_TOKEN_WORD_4', '7668Pf743ae018364a082b2e87f2d2F5');
define('SECURITY_TOKEN_WORD_5', '0f62265227df1b6d6deec36ab4bc5e76');
define('SECURITY_TOKEN_WORD_6', '670df58df5a2Ec63b0a33e054418105a');
define('SECURITY_TOKEN_WORD_7', '6a0d8f756Rfa9c1cd69fed28423ec8ca');
define('SECURITY_TOKEN_WORD_8', '628K7643f52b6d6c34accad8a8dc2867');
define('SECURITY_TOKEN_WORD_9', '1f1Sa6c017f12c1539c4947l234de78a');

function blg_security_choose_token($ts){
	$tokens= array(
		SECURITY_TOKEN_WORD_0,
		SECURITY_TOKEN_WORD_1,
		SECURITY_TOKEN_WORD_2,
		SECURITY_TOKEN_WORD_3,
		SECURITY_TOKEN_WORD_4,
		SECURITY_TOKEN_WORD_5,
		SECURITY_TOKEN_WORD_6,
		SECURITY_TOKEN_WORD_7,
		SECURITY_TOKEN_WORD_8,
		SECURITY_TOKEN_WORD_9
	);
	
	$index= ($ts % 10);	
	
	switch($index){
		case 0: $index= 4; break;
		case 1: $index= 8; break;
		case 2: $index= 1; break;
		case 3: $index= 9; break;
		case 4: $index= 3; break;
		case 5: $index= 7; break;
		case 6: $index= 3; break;
		case 7: $index= 2; break;
		case 8: $index= 6; break;
		case 9: $index= 5; break;
	}
	
	return $tokens[$index]; 
}

function blg_security_token($ts=NULL){
	if(empty($ts))
		$ts= time();
		
	$word= SALT.blg_security_choose_token($ts).$ts;
	$key= md5($word);
	return array($ts, $key);	
}

function blg_security_grant($ts, $key, $max_elapsed_time= SECURITY_MAX_ELAPSED){
	list($ts2, $key2)= blg_security_token($ts);
	
	if(!empty($ts) && !empty($key) && is_int($max_elapsed_time) && $max_elapsed_time>0){		
		$now= time();
		if(($now-$ts)>=$max_elapsed_time){
			blg_msg_add(blg_echo('error:security:ts:elapsed'), true);
			return FALSE;
		}		
	}
	
	return ($key===$key2);		
}

function blg_security_grant_from_input($max_elapsed_time= SECURITY_MAX_ELAPSED){
	$ts = blg_get_input(SECURITY_TS_FIELD);
	$key= blg_get_input(SECURITY_KEY_FIELD);
	return blg_security_grant($ts, $key, $max_elapsed_time);	
}

function blg_security_url($ts=NULL){
	list($ts, $key)= blg_security_token($ts);
	return SECURITY_TS_FIELD.'='.$ts.'&'.SECURITY_KEY_FIELD.'='.$key;		
}

function blg_security_input($ts=NULL){
	list($ts, $key)= blg_security_token($ts);	
	return '<input type="hidden" name="'.SECURITY_TS_FIELD.'" value="'.$ts.'" /><input type="hidden" name="'.SECURITY_KEY_FIELD.'" value="'.$key.'" />';		
}